import axios from "axios";
import {multipartUpload as uploads} from "@/common/xp-multipart/xp-multipart.min.js"

var baseUrl="https://smart1st.net.cn:8080/api"
const instance = axios.create({
  baseURL: baseUrl, // url = base url + request url
  timeout: 5000, // request timeout
  withCredentials: true,
});

//成功后把值设置到缓存
instance.setAccessToken = (accessToken) => {
	instance.defaults.headers['AccessToken'] = accessToken	// 这里用到的存储是localStorage
	uni.setStorageSync('AccessToken',accessToken);
}

//刷新Token请求
function refreshToken() {
  const RefreshToken=uni.getStorageSync('RefreshToken')
  const AccessToken=uni.getStorageSync('AccessToken')
  return instance({method:'post',url: '/auth/refreshToken',headers:{
	  'accessToken':AccessToken,
	  'refreshToken':RefreshToken,
	  'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
	  }})
}

// Token失效清空Token,跳回登录页
function removeToken() {
  uni.clearStorageSync('AccessToken');
  uni.clearStorageSync('RefreshToken');
}

// 请求拦截器
instance.interceptors.request.use(
  config => {
    // 每次发送请求之前判断vuex中是否存在token
    // 如果存在，则统一在http请求的header都加上token，这样后台根据token判断你的登录情况
    // 即使本地存在token，也有可能token是过期的，所以在响应拦截器中要对返回状态进行判断 
    const AccessToken = uni.getStorageSync('AccessToken');
    config.headers['AccessToken'] = AccessToken
	config.headers['Content-Type']='application/x-www-form-urlencoded;charset=utf-8'
    return config;
  },
  error => {
    return Promise.error(error);
  }
);

// 是否正在刷新的标记
let isRefreshing = false
// 重试队列，每一项将是一个待执行的函数形式
let requests = []

// 响应拦截器
instance.interceptors.response.use(
  response => {
    const res = response.data
	
	if (typeof(response.data)=='undefined'){
		let res={
			code:500,
			msg:'服务器错误',
			data:''
		}
		uni.reLaunch({
			url:'/pages/error/error?code='+res.code
		})
		return Promise.reject(res);
	}
	
    // accessToken不合法或未认证 
    if(res.data==null&&(res.code === 401||res.code === 426)){
        removeToken()
        uni.reLaunch({
        	url:'/pages/login/login'
        })
        return Promise.reject(res);
    }
    
	if (res.code === 0) {
		//所有失败拦截
      return Promise.reject(res);
      //return res
    }
	
	if(res.code&&res.code!==200){
		return Promise.reject(res);
	}
	
    return res
  },
  error => {
    console.log(error)
    return Promise.reject();
  }
);

//axios适配器
axios.defaults.adapter = function(config) { //自己定义个适配器，用来适配uniapp的语法
    return new Promise((resolve, reject) => {
        var settle = require('axios/lib/core/settle');
        var buildURL = require('axios/lib/helpers/buildURL');
        uni.request({
            method: config.method.toUpperCase(),
            url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
            header: config.headers,
            data: config.data&&config.method.toUpperCase()=="POST"?JSON.parse(config.data):"",
            dataType: config.dataType,
            responseType: config.responseType,
            sslVerify: config.sslVerify,
            complete: function complete(response) {
                response = {
                    data: response.data,
                    status: response.statusCode,
                    errMsg: response.errMsg,
                    header: response.header,
                    config: config
                };

                settle(resolve, reject, response);
            }
        })
    })
}

instance.upload=function(url,file,data){
	return new Promise((resolve, reject) => {
		const RefreshToken=uni.getStorageSync('RefreshToken')
		const AccessToken=uni.getStorageSync('AccessToken')
		uni.uploadFile({
			url:baseUrl+url,
			filePath:file,
			name:'file',
			formData:data,
			header:{
				  'AccessToken':AccessToken,
				  'RefreshToken':AccessToken,
			},
			success:function(res){
				let result=JSON.parse(res.data)
				resolve(result)
			},
			fail:(res)=>{
				reject(res)
			}
		})
	})
}

instance.uploads=function(url,files,data){
	return new Promise((resolve, reject) => {
		const RefreshToken=uni.getStorageSync('RefreshToken')
		const AccessToken=uni.getStorageSync('AccessToken')
		
		uploads({
		            url: baseUrl+url, //后端接口
		            fields: data,
		            files: files,
					header:{
						  'AccessToken':AccessToken,
						  'RefreshToken':AccessToken,
					},
		            success(res) {
		                resolve(res.data)
		            },
		            fail(err) {
		                reject(err)
		            }
		        })
	})
}

export { instance };